package com.cloudkinto.appletservice.order.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cloudkinto.appletservice.order.AppletOrderRakutenService;
import com.cloudkinto.appletservice.order.vo.rakuten.AppletOrderRakutenDetailResponse;
import com.cloudkinto.appletservice.order.vo.rakuten.AppletOrderRakutenListRes;
import com.cloudkinto.common.constant.SysConstant;
import com.cloudkinto.common.error.ErrorEnum;
import com.cloudkinto.common.exception.BizException;
import com.cloudkinto.common.exception.BizExceptionI18;
import com.cloudkinto.common.exception.NotSufficientFundsException;
import com.cloudkinto.common.utils.TimeUtils;
import com.cloudkinto.common.web.PageResult;
import com.cloudkinto.common.web.SingleResult;
import com.cloudkinto.dao.*;
import com.cloudkinto.entity.*;
import com.cloudkinto.service.email.MailSenderService;
import com.cloudkinto.service.finance.CompanyAccountService;
import com.cloudkinto.service.order.OrderRakutenPackageService;
import com.cloudkinto.service.order.OrderRakutenProductService;
import com.cloudkinto.service.order.vo.OrderRakutenSysTipsReq;
import com.cloudkinto.service.orderoutput.OrderOutputService;
import com.cloudkinto.service.orderoutput.vo.OrderOutputAddReq;
import com.cloudkinto.service.orderoutput.vo.OrderOutputPackageAddReq;
import com.cloudkinto.service.orderoutput.vo.OrderOutputProductAddReq;
import com.cloudkinto.service.region.JpRegionService;
import com.cloudkinto.service.shipprice.ShipPriceService;
import com.cloudkinto.service.shop.ShopService;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.*;

/**
 * <p>
 * service实现类
 * </p>
 *
 * @author 张永远
 * @since 2020-06-03
 */
@Service
@Transactional(rollbackFor = Exception.class)//事务回滚
public class AppletOrderRakutenServiceImpl extends ServiceImpl<OrderRakutenDao, OrderRakutenDo> implements AppletOrderRakutenService {
    private final Logger logger = LoggerFactory.getLogger(getClass());

    @Autowired
    private OrderRakutenDao dao;
    @Autowired
    private OrderRakutenPackageDao packageDao;
    @Autowired
    private OrderRakutenProductDao productDao;
    @Autowired
    private ShopService mShopService;
    @Autowired
    private OrderRakutenProductService rakutenProductService;
    @Autowired
    private OrderRakutenPackageService rakutenPackageService;

    @Autowired
    private ProductInfoDao productInfoDao;
    @Autowired
    private ProductSkuMapDao productSkuMapDao;

    @Autowired
    private OrderOutputService outputService;
    @Autowired
    private OperateRecordDao operateRecordDao;
    @Autowired
    private CompanyAccountService companyAccountService;
    @Value("${gbc.template.filePath}")
    private String templatePath;

    private final int[] orderProgressComm = new int[]{200, 300, 500, 900};
    private final int[] orderProgressUnConfirm = new int[]{100};
    private final String orderType1 = "1";
    private final String orderType3 = "3";
    @Autowired
    private ShopDao shopDao;
    @Autowired
    private UserDao userDao;
    @Autowired
    private ShipPriceService shipPriceService;
    @Autowired
    private StorageDao storageDao;
    @Autowired
    private StockRecordDao stockDao;
    @Autowired
    private CompanyDao companyDao;
    @Autowired
    private JpRegionService mRegionService;
    @Autowired
    private MailSenderService mailService;
    @Autowired
    private OrderRakutenShippingDao rakutenShippingDao;


    @Override
    public AppletOrderRakutenDetailResponse detail(Long id) {
        OrderRakutenDo entityDo = dao.selectById(id);
        if (entityDo == null) throw new BizExceptionI18("no.order.info_id", id);
        AppletOrderRakutenDetailResponse res = new AppletOrderRakutenDetailResponse();
        BeanUtils.copyProperties(entityDo, res);
        return handlerDetailAfter(res, entityDo);
    }

    private AppletOrderRakutenDetailResponse handlerDetailAfter(AppletOrderRakutenDetailResponse res, OrderRakutenDo entityDo) {
        res.setOrderSubAddres(entityDo.getOrderPrefecture() + entityDo.getOrderCity() + entityDo.getOrderSubAddres());

        return res;
    }


    @Override
    public PageResult<AppletOrderRakutenListRes> getListPage(Map<String, String> map) {
        QueryWrapper<OrderRakutenDo> wrapper = queryBuild(map);
        IPage<OrderRakutenDo> page = pageInit(map);
        page = this.page(page, wrapper);
        List<AppletOrderRakutenListRes> resList = handlerListAfter(page.getRecords());
        PageResult result = new PageResult(resList, (int) page.getCurrent(), (int) page.getSize(), (int) page.getTotal(), (int) page.getPages());
        return result;
    }
//
//    @Override
//    public int orderSync(String dateStart, String dateEnd, String dateType, long shopId) {
//        ShopDo shop = verifyShopTokenExist(shopId);
//        String[] orderIds = getRakutenOrderIds(dateStart + "T00:00:00+0900", dateEnd + "T23:59:59+0900", dateType, orderProgressComm,
//                shop.getRakutenSecret(), shop.getRakutenLicense());
//        getOrder(orderIds, shop);
//        return 0;
//    }
//
//    private String[] getRakutenOrderIds(String dateStart, String dateEnd, String dateType, int[] orderProgressList, String secret, String license) {
//        String authorization = "ESA " + Base64.getEncoder().encodeToString((secret + ":" + license).getBytes());
//        String url = GlobalConstants.RakutenURL + "/order/searchOrder/";
////        String url = "http://kintocloud.cn:8080/queryAllShopList";
//        JSONObject jsonObject = new JSONObject();
//        jsonObject.put("startDatetime", dateStart);
//        jsonObject.put("endDatetime", dateEnd);
//        jsonObject.put("dateType", dateType);//1,订单创建时间 3订单支付时间
//        jsonObject.put("orderProgressList", orderProgressList);
//        JSONObject jsonObject1 = new JSONObject();
//        jsonObject1.put("requestRecordsAmount", 1000);
//        jsonObject1.put("requestPage", 1);
//        jsonObject.put("PaginationRequestModel", jsonObject1);
//        JSONObject jsonObject2 = new JSONObject();
//        jsonObject2.put("userid", 1);
//        logger.debug(jsonObject.toJSONString());
//        String jsonData = OkHttpUtils.okHttpRequest(url, HttpMethod.POST.name(), jsonObject.toJSONString(), authorization);
//        JSONObject object = JSONObject.parseObject(jsonData);
////        logger.debug(object.toJSONString());
//        return object.getJSONArray("orderNumberList").toJavaObject(String[].class);
//    }
//
//
//    public String[] searchOrderUnConfirm(String startDate, String endDate, String dateType, String secret, String license) {
//        return getRakutenOrderIds(startDate, endDate, dateType,
//                orderProgressUnConfirm, secret, license);
//    }
//
//    public void getOrder(String[] orderIds, ShopDo shop) {
//        String authorization = "ESA " + Base64.getEncoder().encodeToString((shop.getRakutenSecret() + ":" + shop.getRakutenLicense()).getBytes());
//        if (orderIds.length < 1) return;
//        String url = GlobalConstants.RakutenURL + "/order/getOrder/";
//        for (int i = 0; i <= orderIds.length / 100; i++) {
//            String[] orderLimit;
//            if (i == orderIds.length / 100) {
//                orderLimit = Arrays.copyOfRange(orderIds, i * 100, orderIds.length);
//            } else {
//                orderLimit = Arrays.asList(orderIds).subList(i * 100, (i + 1) * 100).toArray(new String[100]);
//            }
//            JSONObject jsonObject = new JSONObject();
//            jsonObject.put("orderNumberList", orderLimit);
//            logger.debug(jsonObject.toJSONString());
//            String jsonData = OkHttpUtils.okHttpRequest(url, HttpMethod.POST.name(), jsonObject.toJSONString(), authorization);
//            JSONObject object = JSONObject.parseObject(jsonData);
//            List<RakutenOrderModel> orderModels = JSONObject.parseArray(object.getJSONArray("OrderModelList").toJSONString(), RakutenOrderModel.class);
//            List<String> confirmOrderIds = new ArrayList<>();
//            List<String> queryOrderIds = new ArrayList<>();
//            List<RakutenOrderModel> confirmOrders = new ArrayList<>();
//            for (RakutenOrderModel orderModel :
//                    orderModels) {
//                if (orderModel.getOrderProgress() == 100) {
//                    if (orderModel.getIsolatedIslandFlag() == 1 && !shop.getAutoConfirmOrderIslandFlag()) {//1是离岛 0是正常
//                        continue;
//                    }
//                    for (RakutenOrderModel.PackageModelListEntity packageModelListEntity :
//                            orderModel.getPackageModelList()) {
//                        if ((packageModelListEntity.getSenderModel().getPrefecture().contains("北海道")
//                                || packageModelListEntity.getSenderModel().getPrefecture().contains("沖縄"))
//                                && !shop.getAutoConfirmOrderIslandFlag()) {
//                            continue;
//                        }
////                        } else {
////                        boolean b = true;
////                            for (RakutenOrderModel.PackageModelListEntity.ItemModelListEntity itemModelListEntity :
////                                    packageModelListEntity.getItemModelList()) {
////                                List<StockRecordBean> recordBeans = mStockDao.queryAllByShopIdAndSku(
////                                        replaceRakutenItemManageNuber(itemModelListEntity.getItemNumber(), itemModelListEntity.getManageNumber())
////                                        , shopId);
////                                if (recordBeans.size() > 0) {
////                                    for (StockRecordBean recordBean : recordBeans) {
////                                        if (recordBean.getCanSell() - recordBean.getSendOutSell() >= itemModelListEntity.getUnits()) {
////                                            b = true;
////                                            break;
////                                        }
////                                    }
////                                }
////                            }
////                        if (b) {
//                        confirmOrderIds.add(orderModel.getOrderNumber());
//                        confirmOrders.add(orderModel);
////                        }
//                    }
//                } else {
//                    saveRakutenOrder(orderModel, shop.getId(), shop.getCompanyId());
////                    if (orderModel.getOrderProgress() == 300)
////                        queryOrderIds.add(orderModel.getOrderNumber());
//                }
//            }
////            if (shopId == 4 || shopId == 28)
//            if (shop.getAutoSendOutFlag()) {
//                confirmRakutenOrder(confirmOrderIds, shop.getRakutenSecret(), shop.getRakutenLicense(), confirmOrders, shop.getId());
//            }
//            //todo  自动导出到发货单
//            if (shop.getAutoSendOutFlag()) {
//                queryOrder2SendOut(queryOrderIds.toArray(new String[queryOrderIds.size()]), 135l, true, shop.getCompanyId());
//            }
//            logger.debug(object.toJSONString());
//        }
//    }

//    private void saveRakutenOrder(RakutenOrderModel orderModel, Long id, Long companyId) {
//        OrderRakutenDo rakutenDo = new OrderRakutenDo();
//        QueryWrapper wrapper = new QueryWrapper();
//        wrapper.eq("order_number", orderModel.getOrderNumber());
//        OrderRakutenDo orderRakutenDo = baseMapper.selectOne(wrapper);
//        if (orderRakutenDo != null) {
//            rakutenDo = orderRakutenDo;
//        } else {
//            rakutenDo.setCompanyId(companyId);
//            rakutenDo.setShopId(id);
//        }
//        BeanUtils.copyProperties(orderModel, rakutenDo);
//        //日期时间格式
//        if (rakutenDo.getOrderProgress() == 500 || rakutenDo.getOrderProgress() == 900) {
//            rakutenDo.setIsSendOut(1);
//        }
//        rakutenDo.setOrderDatetime(replaceStrDateFromat(orderModel.getOrderDatetime()));
//        rakutenDo.setOrderFixDatetime(replaceStrDateFromat(orderModel.getOrderFixDatetime()));
//        rakutenDo.setShopOrderCfmDatetime(replaceStrDateFromat(orderModel.getShopOrderCfmDatetime()));
//        rakutenDo.setShippingInstDatetime(replaceStrDateFromat(orderModel.getShippingInstDatetime()));
//        rakutenDo.setShippingCmplRptDatetime(replaceStrDateFromat(orderModel.getShippingCmplRptDatetime()));
//        rakutenDo.setRequestPrice((orderModel.getRequestPrice().floatValue()));
//        if (!org.springframework.util.StringUtils.isEmpty(orderModel.getShippingTerm())) {
//            if (orderModel.getShippingTerm().length() > 3) {
//                rakutenDo.setShippingTerm(orderModel.getShippingTerm().substring(0, 2) + "-" + orderModel.getShippingTerm().substring(2));
//            } else if (orderModel.getShippingTerm().length() > 1) {
//                rakutenDo.setShippingTerm(orderModel.getShippingTerm().substring(0, 1) + "-" + orderModel.getShippingTerm().substring(1));
//            }
//        }
//        String tips = orderModel.getRemarks().replaceAll("\\[配送日時指定:\\]", "").replaceAll("\\n", "");
//        if (tips.length() > 100)
//            tips = tips.substring(0, 97) + "...";
//        rakutenDo.setRemarks(tips);
//        rakutenDo.setSystemMemo(orderModel.getMemo());
//        //订购人信息
//        rakutenDo.setOrderCity(orderModel.getOrdererModel().getCity());
//        rakutenDo.setOrderSubAddres(orderModel.getOrdererModel().getSubAddress());
//        rakutenDo.setOrderEmailAddress(orderModel.getOrdererModel().getEmailAddress());
//        rakutenDo.setOrderPhoneNumber(orderModel.getOrdererModel().getPhoneNumber1() + "-" + orderModel.getOrdererModel().getPhoneNumber2() + "-" + orderModel.getOrdererModel().getPhoneNumber3());
//        rakutenDo.setOrderPostCode(orderModel.getOrdererModel().getZipCode1() + "-" + orderModel.getOrdererModel().getZipCode2());
//        rakutenDo.setOrderPrefecture(orderModel.getOrdererModel().getPrefecture());
//        rakutenDo.setOrderName(orderModel.getOrdererModel().getFamilyName() + " " + orderModel.getOrdererModel().getFirstName());
//        rakutenDo.setOrderFamilyNameKana(orderModel.getOrdererModel().getFamilyNameKana());
//        rakutenDo.setOrderFirstNameKana(orderModel.getOrdererModel().getFirstNameKana());
//        rakutenDo.setOrderBirthday(orderModel.getOrdererModel().getBirthYear() + "-" + orderModel.getOrdererModel().getBirthMonth() + "-" + orderModel.getOrdererModel().getBirthDay());
//        rakutenDo.setOrderSex(rakutenDo.getOrderSex());
//        //
//        if (orderModel.getPointModel() != null)
//            rakutenDo.setUsedPoint(orderModel.getPointModel().getUsedPoint());
//        if (orderModel.getDeliveryModel() != null)
//            rakutenDo.setDeliveryName(orderModel.getDeliveryModel().getDeliveryName());
//        if (orderModel.getCouponModelList() != null && orderModel.getCouponModelList().size() > 0) {
//            rakutenDo.setUsedCouponTotalPrice(orderModel.getCouponModelList().get(0).couponTotalPrice);
//        }
//        saveOrUpdate(rakutenDo);
//        for (RakutenOrderModel.PackageModelListEntity packageModelListEntity :
//                orderModel.getPackageModelList()) {
//            OrderRakutenPackageDo rakutenPackageInfo = new OrderRakutenPackageDo();
//            BeanUtils.copyProperties(packageModelListEntity, rakutenPackageInfo);
//            List<OrderRakutenProductDo> rakutenProductInfos = new ArrayList<>();
//            StringBuilder sb = new StringBuilder();
//            for (RakutenOrderModel.PackageModelListEntity.ItemModelListEntity itemModelListEntity :
//                    packageModelListEntity.getItemModelList()) {
//                OrderRakutenProductDo productInfo = new OrderRakutenProductDo();
//                BeanUtils.copyProperties(itemModelListEntity, productInfo);
//                productInfo.setPrice(Float.valueOf(itemModelListEntity.getPrice()));
//                if (companyId == 1) {
//                    productInfo.setItemNumber(replaceRakutenItemManageNuber(itemModelListEntity.getItemNumber(), itemModelListEntity.getManageNumber()));
//                } else {
//                    productInfo.setItemNumber(itemModelListEntity.getItemNumber());
//                }
//                if (itemModelListEntity.getDelvdateInfo() != null) {
//                    if (itemModelListEntity.getDelvdateInfo().contains("予約販売")) {
//                        rakutenDo.setOrderType(6);
//                        rakutenDo.setSystemMemo(itemModelListEntity.getDelvdateInfo());
//                    } else if (itemModelListEntity.getDelvdateInfo().contains("あす楽")) {
//                        rakutenDo.setAsurakuFlag(1);
//                        rakutenDo.setSystemMemo("あす楽" + (rakutenDo.getSystemMemo() == null ? "" : (" " + rakutenDo.getSystemMemo())));
//                    }
//                }
//                productInfo.setBasketId(packageModelListEntity.getBasketId());
//                rakutenProductInfos.add(productInfo);
//                if (sb.length() > 0) sb.append(",");
//                sb.append(productInfo.getItemNumber());
//            }
//            rakutenDo.setCommoditySku(sb.toString());
//            updateById(rakutenDo);
//            rakutenProductService.saveOrUpdateProductList(rakutenProductInfos);
//            rakutenPackageInfo.setOrderId(rakutenDo.getId());
//            //收货人信息
//            rakutenPackageInfo.setOrderCity(packageModelListEntity.getSenderModel().getCity());
//            rakutenPackageInfo.setOrderSubAddres(packageModelListEntity.getSenderModel().getSubAddress());
////            rakutenPackageInfo.set(packageModelListEntity.getSenderModel().getEmailAddress());
//            rakutenPackageInfo.setOrderPhoneNumber(packageModelListEntity.getSenderModel().getPhoneNumber1() + "-" + packageModelListEntity.getSenderModel().getPhoneNumber2() + "-" + packageModelListEntity.getSenderModel().getPhoneNumber3());
//            rakutenPackageInfo.setOrderPostCode(packageModelListEntity.getSenderModel().getZipCode1() + "-" + packageModelListEntity.getSenderModel().getZipCode2());
//            rakutenPackageInfo.setOrderPrefecture(packageModelListEntity.getSenderModel().getPrefecture());
//            rakutenPackageInfo.setOrderName(packageModelListEntity.getSenderModel().getFamilyName() + " " + packageModelListEntity.getSenderModel().getFirstName());
//            rakutenPackageInfo.setOrderFamilyNameKana(packageModelListEntity.getSenderModel().getFamilyNameKana());
//            rakutenPackageInfo.setOrderFirstNameKana(packageModelListEntity.getSenderModel().getFirstNameKana());
//            for (ShippingModelEntity shippingModelEntity : packageModelListEntity.getShippingModelList()) {
//                OrderRakutenShippingDo shippingDo = new OrderRakutenShippingDo();
//                shippingDo.setPackageId(packageModelListEntity.getBasketId());
//                shippingDo.setDeliveryCompany(shippingModelEntity.getDeliveryCompany());
//                shippingDo.setDeliveryCompanyName(shippingModelEntity.getDeliveryCompanyName());
//                shippingDo.setShippingDate(shippingModelEntity.getShippingDate());
//                shippingDo.setShippingDetailId(shippingModelEntity.getShippingDetailId());
//                shippingDo.setShippingNumber(shippingModelEntity.getShippingNumber());
//                if (rakutenShippingDao.selectById(shippingModelEntity.getShippingDetailId()) == null) {
//                    rakutenShippingDao.insert(shippingDo);
//                } else {
//                    rakutenShippingDao.updateById(shippingDo);
//                }
//            }
//            rakutenPackageService.saveOrUpdatePackage(rakutenPackageInfo);
//        }
//
//    }
//
//    private String replaceStrDateFromat(String orderDatetime) {
//        if (StringUtils.isEmpty(orderDatetime)) return "";
//        return orderDatetime.replace("T", " ").replace("+0900", "");
//    }
//
//    private String replaceRakutenItemManageNuber(String itemNumber, String manageNumber) {
//        itemNumber = itemNumber.replaceAll("(?i)" + manageNumber, "");
//        return itemNumber;
//    }
//
//    private void confirmRakutenOrder(List<String> confirmOrderIds, String rakutenSecret, String rakutenLicense, List<RakutenOrderModel> confirmOrders, Long shopId) {
//        if (confirmOrderIds.size() < 1) return;
//        String authorization = "ESA " + Base64.getEncoder().encodeToString((rakutenSecret + ":" + rakutenLicense).getBytes());
//        String url = GlobalConstants.RakutenURL + "/order/confirmOrder/";
////        String url = "http://kintocloud.cn:8080/queryAllShopList";
//        JSONObject jsonObject = new JSONObject();
//        jsonObject.put("orderNumberList", confirmOrderIds);
//        logger.debug(jsonObject.toJSONString());
////        String jsonData = OkHttpUtils.okHttpRequest(url, HttpMethod.POST.name(), jsonObject.toJSONString(), authorization);
////        JSONObject object = JSONObject.parseObject(jsonData);
//        //todo 配信   freemaker
//        Session session = mailService.initRakutenMailSession();
//        Transport transport = null;
////        if (shopId == 4 || shopId == 28) {
////            transport = mailService.initRakutenMailTransport(session);
////        } else if (shopId == 63) {
////            transport = mailService.initRakutenMailTransport(session, "382110", "l1baRYIl7t");
////        } else {
////            transport = mailService.initRakutenMailTransport(session, "377156", "D7TXygKGZ6");
////        }
////        Session session = mailService.initMailSession();
////        Transport transport = mailService.initMailTransport(session);
//        for (String orderNumber :
//                confirmOrderIds) {
//            QueryWrapper queryWrapper = new QueryWrapper();
//            queryWrapper.eq("order_number", orderNumber);
//            OrderRakutenDo rakutenDo = dao.selectOne(queryWrapper);
//            QueryWrapper packageWrapper = new QueryWrapper();
//            packageWrapper.eq("oreder_id", rakutenDo.getId());
//            OrderRakutenPackageDo orderRakutenPackageDo = packageDao.selectOne(packageWrapper);
//            QueryWrapper productWrapper = new QueryWrapper();
//            productWrapper.eq("basket_id", orderRakutenPackageDo.getBasketId());
//            List<OrderRakutenProductDo> orderRakutenProductList = productDao.selectList(productWrapper);
//            switch (shopId.intValue()) {
////                case 4:
////                    mailService.sendEmailRakuten(session, transport, "【FUTATABI】注文確定のお知らせ",
////                            getConfirmEmailTemplate(rakutenDo, orderRakutenPackageDo, orderRakutenProductList, shopId),
////                            orderModel.getOrdererModel().getEmailAddress()
////                            , "rakuten_service@sanchoum.com", "text/html;charset=Shift-JIS");
//
////                    break;
////                case 28:
////                    mailService.sendEmailRakuten(session, transport, "【FUTATABI】注文確定のお知らせ",
////                            getConfirmEmailTemplate(rakutenDo, orderRakutenPackageDo, orderRakutenProductList, shopId),
////                            orderModel.getOrdererModel().getEmailAddress()
////                            , "rakuten_service@sanchoum.com", "text/html;charset=Shift-JIS");
////                    break;
////                case 44:
////                    mailService.sendEmailRakuten(session, transport, "【OneTigris Gear楽天市場店】ご注文ありがとうございます！",
////                            getConfirmEmailTemplate(rakutenDo, orderRakutenPackageDo, orderRakutenProductList, shopId),
////                            orderModel.getOrdererModel().getEmailAddress()
////                            , "kuma@onetigris.com", "icey@onetigris.com", "text/html;charset=Shift-JIS");
////                    break;
////                case 63:
////                    mailService.sendEmailRakuten(session, transport, "【YASUYOSHI】注文確定のお知らせ",
////                            getConfirmEmailTemplate(rakutenDo, orderRakutenPackageDo, orderRakutenProductList, shopId),
////                            orderModel.getOrdererModel().getEmailAddress()
////                            , "yasuyoshi@sanchoum.com", "gongbensong@sanchoum.com", "text/html;charset=Shift-JIS");
////                    break;
//                default:
////                    mailService.sendEmail(session, transport, String.format("【%s】注文確定のお知らせ", shopDao.selectById(shopId).getShopName()),
////                            getConfirmEmailTemplate(rakutenDo, orderRakutenPackageDo, orderRakutenProductList, shopId),
////                            "770403372@qq.com");
//                    break;
//            }
////            logger.debug(getConfirmEmailTemplate(rakutenDo, orderRakutenPackageDo, orderRakutenProductList, shopId));
//
//        }
//        mailService.transportClose(transport);
//
//    }
//
//    private String getConfirmEmailTemplate(OrderRakutenDo orderModel, OrderRakutenPackageDo orderRakutenPackageDo, List<OrderRakutenProductDo> orderRakutenProductList, Long shopId) {
//        try {
//            return FreeMarkerUtils.createRakutentConfirmMailTemplate(orderModel, orderRakutenPackageDo, orderRakutenProductList, templatePath + "rakuten_confirm_" + shopId + ".ftl");
//        } catch (Exception e) {
//            e.printStackTrace();
//            logger.error(orderModel.getOrderNumber() + "发信失败");
//            //todo 写入异常日志通知顾客
//        }
//        return "";
//    }
//
//    private String getSendOutEmailTemplate(OrderRakutenDo orderModel, OrderRakutenPackageDo orderRakutenPackageDo, List<OrderRakutenProductDo> orderRakutenProductList, ShippingModelEntity shippingModelEntity, Long shopId) {
//        try {
//            return FreeMarkerUtils.createRakutenSendOutMailTemplate(orderModel, orderRakutenPackageDo, orderRakutenProductList,
//                    shippingModelEntity, templatePath + "rakuten_sendout_" + shopId + ".ftl");
//        } catch (Exception e) {
//            e.printStackTrace();
//            logger.error(orderModel.getOrderNumber() + "发信失败");
//            //todo 写入异常日志通知顾客
//        }
//        return "";
//    }
//
//
//    private void updateRakutenOrderSendOut(String orderNumber) {
//        UpdateWrapper wrapper = new UpdateWrapper();
//        wrapper.eq("order_number", orderNumber);
//        wrapper.set("is_upload_express", 1);
//        update(wrapper);
//
//    }
//
//    private void updateRakutenOrderSendMail(String orderNumber) {
//        UpdateWrapper wrapper = new UpdateWrapper();
//        wrapper.eq("order_number", orderNumber);
//        wrapper.set("is_upload_express", 1);
//        update(wrapper);
//
//    }
//
//
//    /**
//     * 验证该店铺是否有APItoken
//     *
//     * @param shopId
//     * @return
//     */
//    private ShopDo verifyShopTokenExist(long shopId) {
//        ShopDo shopBean = mShopService.getShopTokenById(shopId);
//        if (StringUtils.isEmpty(shopBean.getRakutenLicense()) || StringUtils.isEmpty(shopBean.getRakutenSecret())) {
//            throw new BizException("店铺对应平台Token未绑定");
//        }
//        return shopBean;
//    }

    /**
     * 转到发货单
     *
     * @param orderids
     * @param currentUserId
     * @param isAuto
     * @return
     */
    @Override
    public SingleResult queryOrder2SendOut(String[] orderids, Long currentUserId, boolean isAuto, Long companyId) {
        //校验余额是否不足
        sufficientFundsCheck(companyId);
        List<String> failOrders = new ArrayList<>();
        List<OrderOutputAddReq> orderOutputAddReqList = new ArrayList<>();
        for (String orderid :
                orderids) {
            List<OrderOutputAddReq> outputAddReqs = new ArrayList<>();
            try {
                outputAddReqs = sendOutOrder(orderid, isAuto);
            } catch (BizException e) {
                e.printStackTrace();
                failOrders.add(e.getMessage());
            }
            if (outputAddReqs.size() < 1) continue;
            orderOutputAddReqList.addAll(outputAddReqs);
//            Session session = mailService.initMailSession();
//            Transport transport = mailService.initMailTransport(session);
            QueryWrapper queryWrapper = new QueryWrapper();
            queryWrapper.eq("id", orderid);
            OrderRakutenDo rakutenDo = dao.selectOne(queryWrapper);
            operateRecord("点击发货", rakutenDo, currentUserId);
        }
//        List<String> failOrders = new ArrayList<>();
        for (OrderOutputAddReq outputAddReq : orderOutputAddReqList) {
            StringBuilder sku = new StringBuilder();
            int cout = 0;
            for (OrderOutputProductAddReq orderOutputProductAddReq : outputAddReq.getPackageList().get(0).getProductList()) {
                cout = cout + orderOutputProductAddReq.getCount();
                if (org.apache.commons.lang3.StringUtils.isNotBlank(sku)) {
                    sku.append(",");
                }
                sku.append(productInfoDao.selectById(orderOutputProductAddReq.getProductId()).getCommoditySku());
            }
            outputAddReq.setSku(sku.toString());
            outputAddReq.setCount(cout);
        }
        if (isAuto) {
            sendOutMatch(orderOutputAddReqList, currentUserId, companyId);
        }
        Map map = new HashMap();
        map.put("orderList", orderOutputAddReqList);
        map.put("failedList", failOrders);
        map.put("storageList", storageDao.selectList(null));
        return SingleResult.success(map);
    }

    @Override
    public SingleResult queryOrder2SendOutNoPackage(String orderid, Long currentUserId, boolean b, Long companyId) {
        //校验余额是否不足
        sufficientFundsCheck(companyId);
        List<String> failOrders = new ArrayList<>();
        List<OrderOutputAddReq> orderOutputAddReqList = new ArrayList<>();
        try {
            OrderRakutenDo rakutenDo = this.baseMapper.selectById(orderid);
            if (rakutenDo == null) throw new BizExceptionI18("no.order.info_id", rakutenDo.getOrderNumber());
            //订单
            OrderOutputAddReq res = new OrderOutputAddReq();
            res.setOrderType(1);
//        res.setStatus(0);
            res.setSendDate(new Date());
            res.setShopId(rakutenDo.getShopId());
            res.setCompanyId(rakutenDo.getCompanyId());
            res.setOrderNo(rakutenDo.getOrderNumber());
//            res.setTips(rakutenDo.getRemarks());

            res.setDeliveryDate(rakutenDo.getDeliveryDate());
            if ("1".equals(rakutenDo.getShippingTerm())) {
                res.setDeliveryTime("09-12");
            } else {
                res.setDeliveryTime(rakutenDo.getShippingTerm());
            }
            res.setShipmentType(rakutenDo.getAsurakuFlag());//乐天次日达
            QueryWrapper<OrderRakutenPackageDo> wrapper = new QueryWrapper<>();
            wrapper.eq("order_id", orderid);
            List<OrderRakutenPackageDo> packageDoList = packageDao.selectList(wrapper);
            if (packageDoList == null || packageDoList.size() < 1)
                throw new BizExceptionI18("order.no.sku_id", rakutenDo.getOrderNumber());
            if (rakutenDo.getSomeSenderFlag() == null || rakutenDo.getSomeSenderFlag() == 0) {
                OrderRakutenPackageDo packageDo = packageDoList.get(0);//乐天默认一个包裹
                res.setReceiverName(packageDo.getOrderName());
                res.setTelPhone(packageDo.getOrderPhoneNumber());
                res.setPostCode(packageDo.getOrderPostCode());
                res.setArea(packageDo.getOrderPrefecture());
                res.setAddress(packageDo.getOrderCity() + packageDo.getOrderSubAddres());
                res.setCod(res.getCod());
                QueryWrapper<OrderRakutenProductDo> productDoQueryWrapper = new QueryWrapper<>();
                productDoQueryWrapper.eq("basket_id", packageDo.getBasketId());
                List<OrderRakutenProductDo> productDoList = productDao.selectList(productDoQueryWrapper);
                List<OrderOutputProductAddReq> productAddList = new ArrayList<>();
                if (productDoList == null || productDoList.size() < 1)
                    throw new BizExceptionI18("order.no.sku_id", rakutenDo.getOrderNumber());
                double[] size = new double[4];
                long storageId = 0L;
                double shipPirce = 99999D;
                for (OrderRakutenProductDo productDo :
                        productDoList) {
                    List<OrderOutputAddReq> resList = new ArrayList<>();
                    List<StorageDo> storageDoList = storageDao.selectList(null);
                    Long productId = getProductId(productDo.getItemNumber(), rakutenDo.getCompanyId());
                    for (StorageDo storageDo : storageDoList) {//遍历仓库是否都有库存
                        LambdaQueryWrapper<StockRecordDo> wrapper2 = new LambdaQueryWrapper();
                        size = shipPriceService.countSameSkuSize(new double[4], productId, 1);
                        wrapper2.eq(StockRecordDo::getShopId, rakutenDo.getShopId())
                                .eq(StockRecordDo::getProductInfoId, productId)
                                .eq(StockRecordDo::getStorageId, storageDo.getId());
                        StockRecordDo stockRecordDo1 = stockDao.selectOne(wrapper2);
                        int noDeliveredCount1 = stockDao.getOrderOutCount(productId, rakutenDo.getShopId(), storageDo.getId());
                        if (stockRecordDo1 != null && stockRecordDo1.getCanSellCount() - noDeliveredCount1 > 0) {
                            List<ShipPriceDo> shipPriceDos = shipPriceService.queryByRegionAndSize(packageDo.getOrderPostCode(),
                                    size, res.getCod(), res.getShipmentType(), storageDo.getId(), 1, res.getCompanyId());
                            if (shipPriceDos.size() < 1 || shipPriceDos.get(0).getPrice() == 0) continue;
                            if (shipPirce > shipPriceDos.get(0).getPrice()) {//选择最便宜的价格
                                shipPirce = shipPriceDos.get(0).getPrice();
                                storageId = storageDo.getId();
                            }
                        }
                    }

                    OrderOutputProductAddReq productDetail = new OrderOutputProductAddReq();
                    productDetail.setProductId(productId);
                    productDetail.setCount(productDo.getUnits());
                    productAddList = new ArrayList<>();
                    productAddList.add(productDetail);
                    OrderOutputPackageAddReq packageDetail = new OrderOutputPackageAddReq();
                    packageDetail.setProductList(productAddList);
                    OrderOutputAddReq addReq = new OrderOutputAddReq();
                    BeanUtils.copyProperties(res, addReq);
                    List<OrderOutputPackageAddReq> packageAddReqList = new ArrayList<>();
                    packageAddReqList.add(packageDetail);
                    addReq.setStorageId(storageId);
                    addReq.setPackageList(packageAddReqList);
                    if (storageId == 0) {
                        failOrders.add("(" + productDo.getItemNumber() + ")库存不足");
                    } else {
                        resList.add(addReq);
                    }
                    orderOutputAddReqList.addAll(resList);
                }
            }
        } catch (BizException e) {
            e.printStackTrace();
            failOrders.add(e.getMessage());
        }
//            Session session = mailService.initMailSession();
//            Transport transport = mailService.initMailTransport(session);
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("id", orderid);
        OrderRakutenDo rakutenDo = dao.selectOne(queryWrapper);
        operateRecord("点击发货", rakutenDo, currentUserId);
//        List<String> failOrders = new ArrayList<>();

        for (OrderOutputAddReq outputAddReq : orderOutputAddReqList) {
            StringBuilder sku = new StringBuilder();
            int cout = 0;
            for (OrderOutputProductAddReq orderOutputProductAddReq : outputAddReq.getPackageList().get(0).getProductList()) {
                cout = cout + orderOutputProductAddReq.getCount();
                if (org.apache.commons.lang3.StringUtils.isNotBlank(sku)) {
                    sku.append(",");
                }
                sku.append(productInfoDao.selectById(orderOutputProductAddReq.getProductId()).getCommoditySku());
            }
            outputAddReq.setSku(sku.toString());
            outputAddReq.setCount(cout);
        }
        if (b) {
            sendOutMatch(orderOutputAddReqList, currentUserId, companyId);
        }
        Map map = new HashMap();
        map.put("orderList", orderOutputAddReqList);
        map.put("failedList", failOrders);
        map.put("storageList", storageDao.selectList(null));
        return SingleResult.success(map);
    }

    @Override
    public SingleResult sendOutMatch(List<OrderOutputAddReq> orderOutputAddReqList, Long userId, Long companyId) {
        List<String> failOrders = outputService.addRakutenList(orderOutputAddReqList, userId);
        if (failOrders.size() > 0) {
            return SingleResult.failure("300", SysConstant.EXPORT_OUT_ORDER_SUCCESS_ID,  failOrders,orderOutputAddReqList.size() - failOrders.size());
        } else {
            return SingleResult.success(failOrders);
        }
    }

    private void sufficientFundsCheck(Long companyId) {
        if (!companyAccountService.getIsDue(companyId)) {
            throw new NotSufficientFundsException(ErrorEnum.NOT_SUFFICIENT_FUNDS);
        }
    }

    private List<OrderOutputAddReq> sendOutOrder(String orderid, boolean b) {
        OrderRakutenDo rakutenDo = this.baseMapper.selectById(orderid);
        if (rakutenDo == null) throw new BizExceptionI18("no.order.info_id", rakutenDo.getOrderNumber());
        List<OrderOutputAddReq> resList = new ArrayList<>();
        //订单
        OrderOutputAddReq res = new OrderOutputAddReq();
        res.setOrderType(1);
//        res.setStatus(0);
        res.setSendDate(new Date());
        res.setShopId(rakutenDo.getShopId());
        res.setCompanyId(rakutenDo.getCompanyId());
        res.setOrderNo(rakutenDo.getOrderNumber());
        res.setTips(rakutenDo.getRemarks());

        res.setDeliveryDate(rakutenDo.getDeliveryDate());
        if ("1".equals(rakutenDo.getShippingTerm())) {
            res.setDeliveryTime("09-12");
        } else {
            res.setDeliveryTime(rakutenDo.getShippingTerm());
        }
        res.setShipmentType(rakutenDo.getAsurakuFlag());//乐天次日达
        QueryWrapper<OrderRakutenPackageDo> wrapper = new QueryWrapper<>();
        wrapper.eq("order_id", orderid);
        List<OrderRakutenPackageDo> packageDoList = packageDao.selectList(wrapper);
        if (packageDoList == null || packageDoList.size() < 1)
            throw new BizExceptionI18("order.no.sku_id", rakutenDo.getOrderNumber());
        if (rakutenDo.getSomeSenderFlag() == null || rakutenDo.getSomeSenderFlag() == 0) {
            OrderRakutenPackageDo packageDo = packageDoList.get(0);//乐天默认一个包裹
            res.setReceiverName(packageDo.getOrderName());
            res.setTelPhone(packageDo.getOrderPhoneNumber());
            res.setPostCode(packageDo.getOrderPostCode());
            res.setArea(packageDo.getOrderPrefecture());
            res.setAddress(packageDo.getOrderCity() + packageDo.getOrderSubAddres());
            res.setCod(res.getCod());


            QueryWrapper<OrderRakutenProductDo> productDoQueryWrapper = new QueryWrapper<>();
            productDoQueryWrapper.eq("basket_id", packageDo.getBasketId());
            List<OrderRakutenProductDo> productDoList = productDao.selectList(productDoQueryWrapper);
            if (productDoList == null || productDoList.size() < 1)
                throw new BizExceptionI18("order.no.sku_id", rakutenDo.getOrderNumber());
            double[] size = new double[4];
            Double shipPirce = 99999d;
            Long storageId = 0L;
            //一单一个产品
            if (productDoList.size() == 1 && productDoList.get(0).getUnits() == 1) {
                Long productId = getProductId(productDoList.get(0).getItemNumber(), rakutenDo.getCompanyId());
                if (productId == null)
                    throw new BizExceptionI18("order.no.sku.info_id", rakutenDo.getOrderNumber(), productDoList.get(0).getItemNumber());
                size = shipPriceService.countSameSkuSize(size, productId, productDoList.get(0).getUnits());
                Long stateId = mRegionService.getStateIdByPostCode(packageDo.getOrderPostCode());
                if (stateId <= 8) {//大阪地区优先发货仓库
                    storageId = 9L;
                } else {//东京仓库优先发货仓库
                    storageId = 10L;
                }
                LambdaQueryWrapper<StockRecordDo> wrapper1 = new LambdaQueryWrapper();
                wrapper1.eq(StockRecordDo::getShopId, rakutenDo.getShopId())
                        .eq(StockRecordDo::getProductInfoId, productId)
                        .eq(StockRecordDo::getStorageId, storageId);
                StockRecordDo stockRecordDo = stockDao.selectOne(wrapper1);
                int noDeliveredCount = stockDao.getOrderOutCount(productId, rakutenDo.getShopId(), storageId);
                if (stockRecordDo != null && stockRecordDo.getCanSellCount() - noDeliveredCount > 0) {//优先仓库有库存，优先仓库发货

                } else {
                    storageId = 0L;
                    List<StorageDo> storageDos = storageDao.selectList(null);
                    for (StorageDo storageDo : storageDos) {//遍历仓库是否都有库存
                        LambdaQueryWrapper<StockRecordDo> wrapper2 = new LambdaQueryWrapper();
                        wrapper2.eq(StockRecordDo::getShopId, rakutenDo.getShopId())
                                .eq(StockRecordDo::getProductInfoId, productId)
                                .eq(StockRecordDo::getStorageId, storageDo.getId());
                        StockRecordDo stockRecordDo1 = stockDao.selectOne(wrapper2);
                        size = shipPriceService.countSameSkuSize(new double[4], productId, productDoList.get(0).getUnits());
                        int noDeliveredCount1 = stockDao.getOrderOutCount(productId, rakutenDo.getShopId(), storageDo.getId());
                        if (stockRecordDo1 != null && stockRecordDo1.getCanSellCount() - noDeliveredCount1 >= productDoList.get(0).getUnits()) {
                            List<ShipPriceDo> shipPriceDos = shipPriceService.queryByRegionAndSize(packageDo.getOrderPostCode(),
                                    size, res.getCod(), res.getShipmentType(), storageDo.getId(), 1, res.getCompanyId());
                            if (shipPriceDos == null || shipPriceDos.size() < 1 || shipPriceDos.get(0).getPrice() == 0)
                                continue;
                            if (shipPirce > shipPriceDos.get(0).getPrice()) {//选择最便宜的价格
                                shipPirce = shipPriceDos.get(0).getPrice();
                                storageId = storageDo.getId();
                            }
                        }
                    }
                }
                List<OrderOutputProductAddReq> productAddList = new ArrayList<>();

                if (storageId == 0)
                    throw new BizExceptionI18("order.no.stock_id", rakutenDo.getOrderNumber(), productDoList.get(0).getItemNumber());
                OrderOutputProductAddReq productDetail = new OrderOutputProductAddReq();
//                productDetail.setOrderId(productDo.getOrderAmazonId());
//                productDetail.setCommoditySku(getProductId(itemsDo.getSellerSku(), orderAmazonDo.getCompanyId()));
                productDetail.setProductId(productId);
                productDetail.setCount(productDoList.get(0).getUnits());
//                productDetail.setStorageSku(null);

                productAddList.add(productDetail);
//捆包信息
                OrderOutputPackageAddReq packageDetail = new OrderOutputPackageAddReq();

                List<OrderOutputPackageAddReq> packageAddReqList = new ArrayList<>();
                packageDetail.setProductList(productAddList);
                packageAddReqList.add(packageDetail);
                res.setStorageId(storageId);
                res.setPackageList(packageAddReqList);
                resList.add(res);
                return resList;
            } else {
                Long stateId = mRegionService.getStateIdByPostCode(packageDo.getOrderPostCode());
                if (stateId <= 7) {//大阪地区优先发货仓库
                    storageId = 9L;
                } else if (stateId >= 8) {//东京仓库优先发货仓库
                    storageId = 10L;
                }
                List<OrderRakutenProductDo> noStockProductList = new ArrayList<>();
                List<OrderOutputProductAddReq> productAddList = new ArrayList<>();
                for (OrderRakutenProductDo productDo :
                        productDoList) {//多个产品判断
                    Long productId = getProductId(productDo.getItemNumber(), rakutenDo.getCompanyId());
                    if (productId == null)
                        throw new BizExceptionI18("order.no.sku.info_id", rakutenDo.getOrderNumber(), productDoList.get(0).getItemNumber());
                    ProductInfoDo productInfoDo = productInfoDao.selectById(productId);
                    LambdaQueryWrapper<StockRecordDo> wrapper1 = new LambdaQueryWrapper();
                    wrapper1.eq(StockRecordDo::getShopId, rakutenDo.getShopId())
                            .eq(StockRecordDo::getProductInfoId, productId)
                            .eq(StockRecordDo::getStorageId, storageId);
                    StockRecordDo stockRecordDo = stockDao.selectOne(wrapper1);
                    int noDeliveredCount = stockDao.getOrderOutCount(productId, rakutenDo.getShopId(), storageId);
                    if (stockRecordDo == null || stockRecordDo.getCanSellCount() - noDeliveredCount < productDo.getUnits()) {
//                            if (stockMap.get(storageDo.getId()) == null) {
//                                stockMap.put(storageDo.getId(), new ArrayList<>());
//                            }
//                            stockMap.get(storageDo.getId()).add(stockRecordDo);
                        noStockProductList.add(productDo);
                        continue;
                    }
//                    });
                    OrderOutputProductAddReq productDetail = new OrderOutputProductAddReq();
                    productDetail.setProductId(productId);
                    productDetail.setCount(productDo.getUnits());
                    productAddList.add(productDetail);

                }
                OrderOutputPackageAddReq packageDetail = new OrderOutputPackageAddReq();
                List<OrderOutputPackageAddReq> packageAddReqList = new ArrayList<>();
                packageDetail.setProductList(productAddList);
                OrderOutputAddReq addReq = new OrderOutputAddReq();
                BeanUtils.copyProperties(res, addReq);
                packageAddReqList.add(packageDetail);
                addReq.setStorageId(storageId);
                addReq.setPackageList(packageAddReqList);
                if (noStockProductList.size() != productDoList.size()) {
                    resList.add(addReq);
                }
                //一个仓库是否发完所有订单
                if (noStockProductList.size() > 0) {
                    if (noStockProductList.size() == 1 && noStockProductList.get(0).getUnits() == 1) {
                        storageId = 0L;
                        Long productId = getProductId(noStockProductList.get(0).getItemNumber(), rakutenDo.getCompanyId());
                        List<StorageDo> storageDos = storageDao.selectList(null);
                        shipPirce = 99999D;
                        for (StorageDo storageDo : storageDos) {//遍历仓库是否都有库存

                            LambdaQueryWrapper<StockRecordDo> wrapper2 = new LambdaQueryWrapper();
                            wrapper2.eq(StockRecordDo::getShopId, rakutenDo.getShopId())
                                    .eq(StockRecordDo::getProductInfoId, productId)
                                    .eq(StockRecordDo::getStorageId, storageDo.getId());
                            StockRecordDo stockRecordDo1 = stockDao.selectOne(wrapper2);
                            size = shipPriceService.countSameSkuSize(new double[4], productId, productDoList.get(0).getUnits());
                            int noDeliveredCount1 = stockDao.getOrderOutCount(productId, rakutenDo.getShopId(), storageDo.getId());
                            if (stockRecordDo1 != null && stockRecordDo1.getCanSellCount() - noDeliveredCount1 >= 0) {
                                List<ShipPriceDo> shipPriceDos = shipPriceService.queryByRegionAndSize(packageDo.getOrderPostCode(),
                                        size, res.getCod(), res.getShipmentType(), storageDo.getId(), 1, res.getCompanyId());
                                if (shipPriceDos.size() < 1 || shipPriceDos.get(0).getPrice() == 0) continue;
                                if (shipPirce > shipPriceDos.get(0).getPrice()) {//选择最便宜的价格
                                    shipPirce = shipPriceDos.get(0).getPrice();
                                    storageId = storageDo.getId();
                                }
                            }
                        }

                        OrderOutputProductAddReq productDetail = new OrderOutputProductAddReq();
                        productDetail.setProductId(productId);
                        productDetail.setCount(noStockProductList.get(0).getUnits());
                        List<OrderOutputProductAddReq> productAddReqLIst = new ArrayList<>();
                        productAddReqLIst.add(productDetail);
                        OrderOutputPackageAddReq packageDetail1 = new OrderOutputPackageAddReq();
                        if (storageId == 0)
                            throw new BizExceptionI18("order.no.stock_id", rakutenDo.getOrderNumber(), productDoList.get(0).getItemNumber());
                        List<OrderOutputPackageAddReq> packageAddReqList1 = new ArrayList<>();
                        packageDetail1.setProductList(productAddReqLIst);
                        OrderOutputAddReq addReq1 = new OrderOutputAddReq();
                        BeanUtils.copyProperties(res, addReq1);
                        packageAddReqList1.add(packageDetail1);
                        addReq1.setStorageId(storageId);
                        addReq1.setPackageList(packageAddReqList1);
                        resList.add(addReq1);
                        return resList;
                    } else {
                        List<OrderRakutenProductDo> productDoListFailed = new ArrayList<>();
                        LambdaQueryWrapper<StorageDo> lambdaQueryWrapper = new LambdaQueryWrapper();
                        lambdaQueryWrapper.eq(StorageDo::getSupportShip, 1).ne(StorageDo::getId, storageId);
                        List<StorageDo> storageDos = storageDao.selectList(lambdaQueryWrapper);
                        List<OrderOutputProductAddReq> productAddReqLIst = new ArrayList<>();
                        if (storageDos != null) {
                            StorageDo storageDo = storageDos.get(0);//遍历支持捆包仓库是否都有库存
                            storageId = storageDo.getId();
                            for (OrderRakutenProductDo productDo :
                                    noStockProductList) {
                                Long productId = getProductId(productDo.getItemNumber(), rakutenDo.getCompanyId());
                                LambdaQueryWrapper<StockRecordDo> wrapper1 = new LambdaQueryWrapper();
                                wrapper1.eq(StockRecordDo::getShopId, rakutenDo.getShopId())
                                        .eq(StockRecordDo::getProductInfoId, productId)
                                        .eq(StockRecordDo::getStorageId, storageDo.getId());
                                StockRecordDo stockRecordDo = stockDao.selectOne(wrapper1);
                                int noDeliveredCount = stockDao.getOrderOutCount(productId, rakutenDo.getShopId(), storageDo.getId());

                                if (stockRecordDo == null || stockRecordDo.getCanSellCount() - noDeliveredCount < productDo.getUnits()) {
                                    productDoListFailed.add(productDo);
                                    continue;
                                }
                                OrderOutputProductAddReq productDetail = new OrderOutputProductAddReq();
                                productDetail.setProductId(productId);
                                productDetail.setCount(productDo.getUnits());
                                productAddReqLIst.add(productDetail);

                            }
                            OrderOutputPackageAddReq packageDetail1 = new OrderOutputPackageAddReq();
                            List<OrderOutputPackageAddReq> packageAddReqList1 = new ArrayList<>();
                            packageDetail1.setProductList(productAddReqLIst);
                            addReq = new OrderOutputAddReq();
                            BeanUtils.copyProperties(res, addReq);
                            packageAddReqList1.add(packageDetail1);
                            addReq.setStorageId(storageId);
                            addReq.setPackageList(packageAddReqList1);
                        } else {
                            productDoListFailed.addAll(noStockProductList);
                        }
                        if (productDoListFailed.size() != noStockProductList.size()) {
                            resList.add(addReq);
                        }
                        if (productDoListFailed.size() > 0) {//捆包仓库无库存，分别发
                            LambdaQueryWrapper<StorageDo> queryWrapper = new LambdaQueryWrapper();
                            queryWrapper.eq(StorageDo::getSupportShip, 0);
                            List<StorageDo> storageDoList = storageDao.selectList(queryWrapper);
                            StringBuilder stringBuilder = new StringBuilder();
                            for (OrderRakutenProductDo productDo :
                                    productDoListFailed) {
                                storageId = 0L;
                                shipPirce = 99999D;
                                Long productId = getProductId(productDo.getItemNumber(), rakutenDo.getCompanyId());
                                for (StorageDo storageDo : storageDoList) {//遍历仓库是否都有库存
                                    LambdaQueryWrapper<StockRecordDo> wrapper2 = new LambdaQueryWrapper();
                                    size = shipPriceService.countSameSkuSize(new double[4], productId, 1);
                                    wrapper2.eq(StockRecordDo::getShopId, rakutenDo.getShopId())
                                            .eq(StockRecordDo::getProductInfoId, productId)
                                            .eq(StockRecordDo::getStorageId, storageDo.getId());
                                    StockRecordDo stockRecordDo1 = stockDao.selectOne(wrapper2);
                                    int noDeliveredCount1 = stockDao.getOrderOutCount(productId, rakutenDo.getShopId(), storageDo.getId());
                                    if (stockRecordDo1 != null && stockRecordDo1.getCanSellCount() - noDeliveredCount1 >= productDo.getUnits()) {
                                        List<ShipPriceDo> shipPriceDos = shipPriceService.queryByRegionAndSize(packageDo.getOrderPostCode(),
                                                size, res.getCod(), res.getShipmentType(), storageDo.getId(), 1, res.getCompanyId());
                                        if (shipPriceDos.size() < 1 || shipPriceDos.get(0).getPrice() == 0) continue;
                                        if (shipPirce > shipPriceDos.get(0).getPrice()) {//选择最便宜的价格
                                            shipPirce = shipPriceDos.get(0).getPrice();
                                            storageId = storageDo.getId();
                                        }
                                    }
                                }

                                OrderOutputProductAddReq productDetail = new OrderOutputProductAddReq();
                                productDetail.setProductId(productId);
                                productDetail.setCount(productDo.getUnits());
                                List<OrderOutputProductAddReq> productAddList1 = new ArrayList<>();
                                productAddList1.add(productDetail);
                                packageDetail = new OrderOutputPackageAddReq();

                                packageAddReqList = new ArrayList<>();
                                packageDetail.setProductList(productAddList1);
                                addReq = new OrderOutputAddReq();
                                BeanUtils.copyProperties(res, addReq);
                                packageAddReqList.add(packageDetail);
                                addReq.setStorageId(storageId);
                                addReq.setPackageList(packageAddReqList);
                                if (storageId == 0) {
                                    stringBuilder.append("(" + productDo.getItemNumber() + ")");
                                } else {
                                    resList.add(addReq);
                                }
                            }
                            if (stringBuilder.length() > 0) {
                                throw new BizExceptionI18("order.no.stock_id", rakutenDo.getOrderNumber(), stringBuilder.toString());
                            }
                        }
                    }
                }
            }
        } else {
            //多个包裹多个地址
        }
        return resList;
    }

    private Long getProductId(String sellerSku, Long companyId) {
        QueryWrapper productWrapper = new QueryWrapper();
        productWrapper.eq("commodity_sku", sellerSku);
        productWrapper.eq("company_id", companyId);
        ProductInfoDo productInfoDo = productInfoDao.selectOne(productWrapper);
        if (productInfoDo == null) {
            QueryWrapper skuWrapper = new QueryWrapper();
            skuWrapper.eq("sub_sku", sellerSku);
            skuWrapper.eq("company_id", companyId);
            ProductSkuMapDo productSkuMapDo = productSkuMapDao.selectOne(skuWrapper);
            if (productSkuMapDo == null) throw new BizExceptionI18("no.product.info_id", sellerSku);
            return productSkuMapDo.getProductInfoId();
        } else {
            return productInfoDo.getId();
        }
    }

    @Override
    public int setOrderSend(Long[] orderids, Long userId) {
        int count = baseMapper.updateRakutenOrderSend(orderids);
        for (Long orderid : orderids) {
            OrderRakutenDo orderRakutenDo = dao.selectById(orderid);
            operateRecord("标记为发货", orderRakutenDo, userId);
        }
        return count;
    }

    private void operateRecord(String str, OrderRakutenDo orderRakutenDo, Long userId) {
        OperateRecordDo operateRecordDo = new OperateRecordDo();
        operateRecordDo.setDeleteFlag(0);
        operateRecordDo.setThirdId(orderRakutenDo.getId());
        operateRecordDo.setType(5);
        operateRecordDo.setOperateBy(userId);
        operateRecordDo.setOperateTime(new Date());
        operateRecordDo.setContent(str);
        operateRecordDao.insert(operateRecordDo);
    }


    //查询分页列表之后对列表数据的处理
    private List<AppletOrderRakutenListRes> handlerListAfter(List<OrderRakutenDo> list) {
        List<AppletOrderRakutenListRes> result = new ArrayList<>();
        for (OrderRakutenDo sourceDo :
                list) {
            AppletOrderRakutenListRes targetDo = new AppletOrderRakutenListRes();
            BeanUtils.copyProperties(sourceDo, targetDo);
            QueryWrapper wrapper = new QueryWrapper();
            wrapper.eq("order_id", sourceDo.getId());
            List<OrderRakutenPackageDo> packageDoList = packageDao.selectList(wrapper);
            QueryWrapper wrapper1 = new QueryWrapper();
            if (packageDoList == null || packageDoList.size() < 1) continue;
            wrapper1.eq("basket_id", packageDoList.get(0).getBasketId());
            List<OrderRakutenProductDo> productDoList = productDao.selectList(wrapper1);
            targetDo.setShipmentType(sourceDo.getAsurakuFlag());
            result.add(targetDo);
        }
        return result;
    }

    private IPage<OrderRakutenDo> pageInit(Map<String, String> map) {
        IPage<OrderRakutenDo> page = new Page();
        page.setSize(StringUtils.isNotBlank(map.get("pageSize")) ? Long.parseLong(map.get("pageSize")) : 10);
        page.setCurrent(StringUtils.isNotBlank(map.get("current")) ? Long.parseLong(map.get("current")) : 1);
        return page;
    }

    private QueryWrapper<OrderRakutenDo> queryBuild(Map<String, String> map) {
        QueryWrapper<OrderRakutenDo> wrapper = new QueryWrapper<>();
        if (StringUtils.isNotBlank(map.get("keyword"))) {
            wrapper.or(orderRakutenDoQueryWrapper -> {
                orderRakutenDoQueryWrapper.like("order_number", map.get("keyword").trim()).or();
                orderRakutenDoQueryWrapper.like("order_name", map.get("keyword").trim()).or();
                orderRakutenDoQueryWrapper.like("system_memo", map.get("keyword").trim()).or();
                orderRakutenDoQueryWrapper.like("order_phone_number", map.get("keyword").trim()).or();
                orderRakutenDoQueryWrapper.like("commodity_sku", map.get("keyword").trim());
            });
        }
        if (map.containsKey("isSend"))
            wrapper.eq("is_send_out", map.get("isSend"));
        if (map.containsKey("orderProgress"))
            wrapper.eq("order_progress", map.get("orderProgress"));
        if (map.containsKey("shipType"))
            wrapper.eq("asuraku_flag", map.get("shipType"));
        if (map.containsKey("shopId"))
            wrapper.eq("shop_id", map.get("shopId"));
        wrapper.eq("company_id", map.get("companyId"));
        if (orderType1.equals(map.get("dateType"))) {
            if (StringUtils.isNotBlank(map.get("dateEnd")))
                wrapper.lt("order_datetime", map.get("dateEnd"));
            if (StringUtils.isNotBlank(map.get("dateStart")))
                wrapper.gt("order_datetime", map.get("dateStart"));
        } else {//默认用户付款时间
            if (StringUtils.isNotBlank(map.get("dateEnd"))) {
                String date = TimeUtils.formatDate(TimeUtils.getDateAdd(TimeUtils.parseDate(map.get("dateEnd")), 1));
                wrapper.lt("order_fix_datetime", date);
            }
            if (StringUtils.isNotBlank(map.get("dateStart")))
                wrapper.gt("order_fix_datetime", map.get("dateStart"));
        }
        wrapper.orderByDesc("order_fix_datetime");
        return wrapper;
    }


    @Override
    public List<Map> ordersyncInit(Long currentUserId, Long companyId) {
        List<Map> shopList = new ArrayList<>();
        UserDo userDo = userDao.selectById(currentUserId);
        if (userDo == null) throw new BizExceptionI18("no.user.info");
        QueryWrapper shopWrapper = new QueryWrapper();
        if (userDo.getShopId() != null)
            shopWrapper.eq("id", userDo.getShopId());
        shopWrapper.eq("company_id", companyId);
        shopWrapper.eq("platform_id", 2);
        List<ShopDo> shopDoList = shopDao.selectList(shopWrapper);
        if (!CollectionUtils.isEmpty(shopDoList)) {
            for (ShopDo shopDo : shopDoList) {
                Map shopMap = new HashMap();
                shopMap.put("id", shopDo.getId());
                shopMap.put("value", shopDo.getShopName());
                shopList.add(shopMap);
            }
        }
        return shopList;
    }

    @Override
    public SingleResult updateSysTips(OrderRakutenSysTipsReq sysTipsReq, Long userId, Long companyId) {
        OrderRakutenDo rakutenDo = baseMapper.selectById(sysTipsReq.getId());
        if (rakutenDo == null) {
            throw new BizExceptionI18("no.order.info");
        }
        rakutenDo.setSystemMemo(sysTipsReq.getDesc());
        updateById(rakutenDo);
        return SingleResult.success(rakutenDo);
    }

    @Override
    public SingleResult updateSysTipsInti(Long orderId) {
        OrderRakutenDo rakutenDo = baseMapper.selectById(orderId);
        if (rakutenDo == null) {
            throw new BizExceptionI18("no.order.info");
        }
        return SingleResult.success(rakutenDo.getSystemMemo());
    }
}
